package com.roc.pan.download;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

@Slf4j
public class FileDownloader {

    private static final int BUFFER_SIZE = 4096;
    
    public static final String TEMP_SUFFIX = ".download";

    public static void downloadFile(String fileURL, String saveDir) throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // Check if file is available for download
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // Get file size
            int contentLength = httpConn.getContentLength();

            // Create a buffer for reading the content
            byte[] buffer = new byte[BUFFER_SIZE];

            String realFileName = getFileNameFromUrl(fileURL);

            File tempFile = new File(saveDir + "/" + realFileName + TEMP_SUFFIX);
            FileOutputStream outputStream = new FileOutputStream(tempFile);

            // Read the content in chunks and save it to the file
            int bytesRead = -1;
            int totalBytesRead = 0;
            BigDecimal displayPercent = BigDecimal.ZERO;
            InputStream inputStream = httpConn.getInputStream();

            log.info("开始下载文件：{}", realFileName);
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
                // Display the download percentage
                BigDecimal percent = new BigDecimal((totalBytesRead * 100.0f) / contentLength);
                percent = percent.setScale(1, RoundingMode.HALF_UP);
                if (percent.compareTo(displayPercent) > 0) {
                    displayPercent = percent;
                    log.info("Downloaded " + displayPercent + "% of the file");
                }
            }
            // Close the streams
            outputStream.close();
            inputStream.close();

            // Rename the temp file to the actual file name
            tempFile.renameTo(new File(saveDir + "/" + realFileName));
            log.info("{}下载成功", realFileName);
        } else {
            System.out.println("No file to download. Server replied with HTTP code: " + responseCode);
        }
        httpConn.disconnect();
    }

    public static String getFileNameFromUrl(String url) throws UnsupportedEncodingException {
        String realFileName = url.substring(url.lastIndexOf("/") + 1);
        realFileName = realFileName.substring(0, realFileName.indexOf("?"));
        realFileName = URLDecoder.decode(realFileName, "utf-8");
        return realFileName;
    }

    public static void main(String[] args) {
        try {
            String fileURL = "https://89-cucc-dd.tv002.com/down/2f72421f5338e75ed44e4638ab5352fc/%E4%B8%96%E7%95%8C%E8%BF%91%E7%8E%B0%E4%BB%A3%E5%8F%B2.25%E4%B8%A4%E6%9E%81%E6%A0%BC%E5%B1%80%28%E4%B8%8B%29.mp3?cts=D223A100A142A112F11994&ctp=223A100A142A112&ctt=1675931228&limit=1&spd=50000&ctk=2f72421f5338e75ed44e4638ab5352fc&chk=4493d70f021932b1602e05e282c3ee68-110543131&mtd=1";
            String saveDir = "/Users/sky/Downloads/pan";

            downloadFile(fileURL, saveDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
